import Constants from "../libs/Constants";
import GameData from "../libs/GameData";
import Helper from "../libs/HelperMgr";
import CameraManager from "./CameraManager";
import GameManager from "./GameManager";

const { ccclass, property } = cc._decorator;

@ccclass
export default class Enemy extends cc.Component {


  @property(Number)
  type: number = 0;

  /**目标节点 */
  private target: cc.Node = null;

  /**是否在跳跃 */
  private _jump: boolean = false;
  private _jumpDir: number = 1;
  private _jumpLine: number = 0;
  private _jumpPlayerPos: cc.Vec2 = new cc.Vec2(1, 1);
  private _jumpHeight: number = 300;


  /**是否被击飞 */
  private _flyUp: boolean = false;

  /**是否正在寻找玩家 */
  private _chase: boolean = false;

  /**自由活动方向 */
  private _swingDirection: cc.Vec2 = new cc.Vec2(1, 1);

  /**击飞方向 */
  private _flyUpDirection: cc.Vec2 = new cc.Vec2(1, 1);

  /**是否碰到障碍降落 */
  private _descent: boolean = false;




  /**鱼的大小 */
  private _scale: number = 1;

  /**鱼的透明度 */
  private _opcity: number = 1;


  onLoad() {
    //出生时检测一次距离
    this.getDistance();
    //定时随机改变自由活动朝向
    this.schedule(() => {
      this.changeDirection();
    }, 1);
  }


  
  onCollisionEnter(other) {
    if (other.node.group == 'player') {
      GameManager.instace.playerIsHit = true;
      let force = GameManager.instace.forcePercent*Constants.RodInfo[GameData.instance.playRod].force;
      this.flyUp(force / 10);
    }
    if (other.node.group == 'barrier') {
      this.descent();
    }
  }

  private changeDirection() {
    if (this._chase || this._flyUp || this._descent || this._jump) {
      return;
    }
    let offsetX = 0;
    if (this.node.x > cc.winSize.width - 200) {
      offsetX = -Helper.randAtoB(0, 5)
    } else if (this.node.x < 200) {
      offsetX = Helper.randAtoB(0, 5)
    } else {
      offsetX = Helper.randAtoB(-5, 5)
    }
    let offsetY = 0;
    if (this.node.y < 50) {
      offsetY = Helper.randAtoB(0, 2);
    } else if (this.node.y > GameManager.instace.ground.y - 50) {
      offsetY = -Helper.randAtoB(0, 2);
    } else {
      offsetY = Helper.randAtoB(-2, 2);
    }
    this._swingDirection = new cc.Vec2(offsetX, offsetY)
  }


  private findTarget() {
    if (GameManager.instace.stoshs.childrenCount > 0) {
      let ran = Helper.randAtoB(0, GameManager.instace.stoshs.childrenCount - 1)
      this.target = GameManager.instace.stoshs.children[ran];
    } else {
        this.target = GameManager.instace.player;
      }
  }



  /**
   * 获取与主角的距离
   * 小于300 跳跃
   * 大于1000 寻找玩家
   */
  private getDistance() {
    if (this._flyUp || this._descent) {
      return;
    }
    this.findTarget();
    if (this.target) {
      const distance = Helper.getDistance(this.target.x, this.target.y, this.node.x, this.node.y);
      const distanceHeight = Math.abs(this.node.y - this.target.y);
      if (distance > 1000) {
        this.chase()
      } else if (distance < 300 && distanceHeight < 200) {
        if(this.target.group == "player" && Math.random() <= Constants.EnemyInfo[this.type].playerjumprate){
          this.jump();
        }else if(this.target.group == "stosh" && Math.random() <= Constants.EnemyInfo[this.type].stoshjumprate){
          this.jump()
        }else{
          this.swing();
        }
      } else {
        this.swing();
      }
    } else {
      this.swing();
    }

  }

  /**
   * 跳跃
   */
  private jump() {
    if (this._jump) return;
    this._descent = false;
    this._chase = false;
    this._jump = true;
    this._jumpDir = this.target.x > this.node.x ? 1 : -1;
    this._jumpLine = this.node.y;
    this._jumpPlayerPos = new cc.Vec2(this.target.x, this.target.y);
    this._jumpHeight = Helper.randAtoB(300, 500);
    GameManager.instace.createSpray(new cc.Vec2(this.node.x, this.node.y))
    // console.log('跳');
  }

  /**
   * 自由活动？
   */
  private swing() {
    if (!this._jump) return;
    this._descent = false;
    this._flyUp = false;
    this._chase = false;
    this._jump = false;
    // console.log('自由活动');
  }

  /**
   * 碰到障碍物死亡直降
   */
  private descent() {
    if (this._descent) return;
    this._descent = true
    this._flyUp = false;
    this._chase = false;
    this._jump = false;
  }


  /**
   * 寻找玩家
   */
  private chase() {
    if (this._chase) return;
    this._descent = false;
    this._flyUp = false;
    this._chase = true;
    this._jump = false;
  }

  private flyUp(force) {
    if (this._flyUp) return;
    this._descent = false;
    let offsetX = (this.node.x - GameManager.instace.player.x) * force;
    let offsetY = (this.node.y - GameManager.instace.player.y) * force;
    this._flyUp = true;
    this._chase = false;
    this._jump = false;
    this._flyUpDirection = new cc.Vec2(offsetX / 50, offsetY / 200);
    if (!CameraManager.instance.target) {
      CameraManager.instance.target = this.node;
    }
  }

  /**切换状态 */
  changeState(){
    if(this.type == Constants.EnemyType.duck){
      let normal = this.node.getChildByName("normal")
      let fly = this.node.getChildByName("fly")
      let stream = this.node.getChildByName("stream")
      normal && (normal.active = !this._jump);
      fly && (fly.active = this._jump);
      if(stream){
        if(this._flyUp || this._jump || this._descent){
          stream.active = false
        }else{
          stream.active = this._swingDirection.x != 0;
        }
        let scaleX = 0.8 + Math.abs(this._swingDirection.x) / 5;
        stream.scaleX =  Helper.lerp(stream.scaleX,scaleX,0.2);
      }
      
    }

  }


  _jumpTime = 0;
  _flyTime = 0;
  update() {
    if (GameManager.instace.gameIsStart && !GameManager.instace.gameIsOver) {
      this.changeState();
      if (!this._jump && !this._flyUp && !this._descent) {
        this._opcity = (1 - Math.abs(this.node.y - GameManager.instace.ground.y) / 300) * 255
        this._scale = (1 - Math.abs(this.node.y - GameManager.instace.ground.y) / 300)
        this.node.opacity = this._opcity;
        this.node.scaleY = this._scale;
        if (this.node.x > cc.winSize.width) {
          this.node.x = cc.winSize.width;
        }
        if (this.node.x < 0) {
          this.node.x = 0;
        }
        if (this.node.y > Constants.EnemyInfo[this.type].range.maxY) {
          this.node.y = Constants.EnemyInfo[this.type].range.maxY;
        }
        if (this.node.y < Constants.EnemyInfo[this.type].range.minY) {
          this.node.y = Constants.EnemyInfo[this.type].range.minY;
        }

      }

      if (this._descent) {
        this.node.y -= 10;
        this.node.angle = 90 * this.node.scaleX;
        if (this.node.y < GameManager.instace.ground.y) {
          GameManager.instace.playerIsHit = false;
          CameraManager.instance.target = null;
          GameManager.instace.createSpray(new cc.Vec2(this.node.x, this.node.y))
          this.node.removeFromParent();
          this.node.destroy();
        }
      }
      else if (this._flyUp) {
        this._flyTime += 0.1;
        this.node.angle += 5;
        this.node.x += this._flyUpDirection.x;
        this.node.y += this._flyUpDirection.y - this._flyTime;
        GameManager.instace.gameScore += Constants.EnemyInfo[this.type].score;
        if (this.node.y < GameManager.instace.ground.y) {
          GameManager.instace.playerIsHit = false;
          CameraManager.instance.target = null;
          this.node.destroy();
        }

      } else if (this._jump) {
        /**跳跃 */
        this._jumpTime += 1;
        this.node.opacity = 255;
        this.node.scaleX = -this._scale * this._jumpDir;
        this.node.x += 3 * this._jumpDir;
        this.node.angle = -this.getAngleBetweenPos();
        if (this._jumpTime % 180 == 0) {
          GameManager.instace.createSpray(new cc.Vec2(this.node.x, this.node.y))
          this._jump = false;
        }
        this.node.y = this._jumpLine + Math.sin(this._jumpTime / 180 * Math.PI) * this._jumpHeight;
      } else if (this._chase) {
        /**追逐 */
        this.node.angle = 0;
        this._jumpTime = 0;
        this.getDistance();
        this.node.scaleX = this.node.x < this.target.x ? -this._scale : this._scale
        this.node.x += this.node.x < this.target.x ? this._scale * 3 : -this._scale * 3
        this.node.y += this.node.y < this.target.y ? this._scale * 3 : -this._scale * 3
      } else {
        /**自由活动时，也需要检测距离 */
        this.node.angle = 0;
        this._jumpTime = 0;
        this.getDistance();
        this.node.scaleX = this._swingDirection.x > 0 ? -this._scale : this._scale
        this.node.x += this._swingDirection.x;
        this.node.y += this._swingDirection.y;
      }
    }


  }


  getAngleBetweenPos() {
    var offsetX = this.node.x - this._jumpPlayerPos.x;
    var offsetY = this.node.y - this._jumpPlayerPos.y;
    var angle = Math.atan2(offsetX, offsetY) / Math.PI * 180;
    // console.log("当前角度",angle)
    return angle;
  }
}
